package match_data

import (
	"encoding/json"
	"github.com/spf13/cast"
	messages2 "longmen/server/internal/rpc/tencentim/messages"
	"longmen/server/internal/services/nami/services/sports/basketball/bbcache"
	"longmen/server/internal/services/nami/services/sports/football/fbcache"
	"longmen/server/pkg/common/lib/bytesconv"
)

func GetTextLiveData(roomId string) (historyMsg []string) {
	//嘗試獲取文字直播
	if textMsg, has := textHistory(roomId); has {
		historyMsg = append(historyMsg, textMsg)
	}
	return historyMsg
}

func GetTextLive(roomId string) (string, bool) {
	return textHistory(roomId)
}

func textHistory(roomId string) (string, bool) {
	matchId := cast.ToInt(roomId)
	var numLimit = 140
	var cache string
	cache = bbcache.NewTextLiveCache().GetTextLiveCache(matchId)
	if len(cache) == 0 {
		// ES 查询后，需要组装一个结构体
		es := bbcache.NewTextLiveCache().SearchByEs(matchId, numLimit)
		if len(es) > 0 {
			message := messages2.RoomTextLiveMessage{
				SentMessageStruct: messages2.SentMessageStruct{Type: messages2.RoomTextLiveMessageType},
				TextLive:          es,
			}
			marshal, _ := json.Marshal(message)
			return string(marshal), true
		}
	}

	if len(cache) > 0 {
		return cutTextLiveRecords(cache, numLimit), true
	}

	cache = fbcache.NewTextLiveCache().GetTextLiveCache(matchId)
	if len(cache) == 0 {
		es := fbcache.NewTextLiveCache().SearchByEs(matchId, numLimit)
		if len(es) > 0 {
			message := messages2.RoomTextLiveMessage{
				SentMessageStruct: messages2.SentMessageStruct{Type: messages2.RoomTextLiveMessageType},
				TextLive:          es,
			}
			marshal, _ := json.Marshal(message)
			return string(marshal), true
		}
	}
	if len(cache) > 0 {
		return cutTextLiveRecords(cache, numLimit), true
	}

	return "", false
}

func cutTextLiveRecords(cache string, limit int) string {
	message := messages2.RoomTextLiveMessage{}
	err := json.Unmarshal(bytesconv.StringToBytes(cache), &message)
	if err != nil {
		return ""
	}
	total := len(message.TextLive)
	if total > limit {
		message.TextLive = message.TextLive[total-limit : total]
	}
	marshal, _ := json.Marshal(message)
	return bytesconv.BytesToString(marshal)
}
